<?php
require_once __DIR__ . '/../models/Post.php';

class PostController
{
	private $db;
	private $postModel;

	public function __construct($db)
	{
		$this->db = $db;
		$this->postModel = new Post($db);
	}

	//	获取最热门的攻略帖
	public function getTopPosts()
	{
		try {
			// 从查询参数获取limit值
			$limit = $_GET['limit'] ?? 5;

			$posts = $this->postModel->getTopViewedPosts($limit);

			if (empty($posts)) {
				http_response_code(404);
				echo json_encode(['message' => 'No posts found']);
				return;
			}

			// 格式化响应数据
			$formattedPosts = array_map(function ($post) {
				return [
					'post_id' => $post['id'] ?? null,
					'title' => $post['title'] ?? '',
					'content' => $post['content'] ?? '',
					'view_count' => $post['view_count'] ?? 0,
					'created_at' => $post['created_at'] ?? null,
					'category_id' => $post['category_id'] ?? null,
					'user' => [
						'id' => $post['user_id'],
						'username' => $post['username'],
						'avatar_url' => $post['avatar_url']
					]
				];
			}, $posts);

			echo json_encode([
				'status' => 'success',
				'limit' => (int) $limit,
				'data' => $formattedPosts
			]);

		} catch (Exception $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => 'Failed to retrieve posts',
				'error' => $e->getMessage()
			]);
		}
	}

	//	获取指定分类下的帖子
	public function getPostsByCategory()
	{
		try {
			// 从查询参数获取category_id
			$categoryId = $_GET['category_id'] ?? null;

			if (!$categoryId) {
				http_response_code(400);
				echo json_encode(['error' => 'category_id parameter is required']);
				return;
			}

			$posts = $this->postModel->getPostsByCategory($categoryId);

			if (empty($posts)) {
				header('Content-Type: application/json');
				echo json_encode([]); // 返回空数组
				return;
			}

			// 格式化响应数据
			$formattedPosts = array_map(function ($post) {
				return [
					'post_id' => $post['id'] ?? null,
					'title' => $post['title'] ?? '',
					'content' => $post['content'] ?? '',
					'view_count' => $post['view_count'] ?? 0,
					'created_at' => $post['created_at'] ?? null,
					'category_id' => $post['category_id'] ?? null,
					'user' => [
						'id' => $post['user_id'],
						'username' => $post['username'],
						'avatar_url' => $post['avatar_url']
					]
				];
			}, $posts);

			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'category_id' => (int) $categoryId,
				'count' => count($formattedPosts),
				'data' => $formattedPosts
			]);

		} catch (Exception $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}

	//	搜索帖子
	public function searchPosts()
	{
		try {
			$keyword = $_GET['q'] ?? null;
			$orderBy = $_GET['order_by'] ?? 'view_count';
			$orderDirection = $_GET['order_direction'] ?? 'DESC';

			if (!$keyword) {
				http_response_code(400);
				echo json_encode(['error' => 'Search keyword (q) is required']);
				return;
			}

			$posts = $this->postModel->searchPosts($keyword, $orderBy, $orderDirection);

			if (empty($posts)) {
				http_response_code(404);
				echo json_encode(['message' => 'No posts found matching your search']);
				return;
			}

			$formattedPosts = array_map(function ($post) {
				return [
					'post_id' => $post['id'] ?? null,
					'title' => $post['title'] ?? '',
					'content' => $post['content'] ?? '',
					'view_count' => $post['view_count'] ?? 0,
					'comment_count' => $post['comment_count'] ?? 0,
					'created_at' => $post['created_at'] ?? null,
					'category_id' => $post['category_id'] ?? null,
					'user' => [
						'id' => $post['user_id'],
						'username' => $post['username'],
						'avatar_url' => $post['avatar_url']
					]
				];
			}, $posts);

			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'keyword' => $keyword,
				'count' => count($formattedPosts),
				'data' => $formattedPosts
			]);

		} catch (Exception $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}

	// 获取指定id下的帖子
	public function getPostById()
	{
		try {
			$postId = $_GET['id'] ?? null;

			if (!$postId) {
				http_response_code(400);
				echo json_encode(['error' => 'Post ID parameter is required']);
				return;
			}

			$post = $this->postModel->getPostById($postId);

			// 格式化响应数据
			$formattedPost = [
				'post_id' => $post['id'],
				'title' => $post['title'],
				'content' => $post['content'],
				'view_count' => $post['view_count'],
				'created_at' => $post['created_at'],
				'updated_at' => $post['updated_at'] ?? null,
				'category_id' => $post['category_id'] ?? null,
				'user' => [
					'id' => $post['user_id'],
					'username' => $post['username'],
					'avatar_url' => $post['avatar_url']
				]
			];

			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'data' => $formattedPost
			]);

		} catch (Exception $e) {
			if ($e->getMessage() === "Post not found") {
				http_response_code(404);
				echo json_encode([
					'status' => 'error',
					'message' => 'Post not found'
				]);
			} else {
				http_response_code(500);
				echo json_encode([
					'status' => 'error',
					'message' => $e->getMessage()
				]);
			}
		}
	}

	// 获取指定id下贴子评论
	public function getPostComments()
	{
		try {
			$postId = $_GET['post_id'] ?? null;

			if (!$postId) {
				http_response_code(400);
				echo json_encode(['error' => 'Post ID parameter is required']);
				return;
			}

			$comments = $this->postModel->getCommentsByPostId($postId);

			// 格式化响应数据
			$formattedComments = array_map(function ($comment) {
				return [
					'comment_id' => $comment['id'],
					'content' => $comment['content'],
					'created_at' => $comment['created_at'],
					'updated_at' => $comment['updated_at'] ?? null,
					'user' => [
						'id' => $comment['user_id'],
						'username' => $comment['username'],
						'avatar_url' => $comment['avatar_url']
					]
				];
			}, $comments);

			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'data' => $formattedComments
			]);

		} catch (Exception $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}

	// 插入评论
	public function insertComment()
	{
		try {
			// 获取请求数据
			$data = json_decode(file_get_contents('php://input'), true);

			// 验证必要字段
			if (empty($data['post_id']) || empty($data['user_id']) || empty($data['content'])) {
				http_response_code(400);
				echo json_encode(['error' => 'Missing required fields (post_id, user_id, content)']);
				return;
			}

			// 验证内容长度
			if (strlen($data['content']) > 1000) {
				http_response_code(400);
				echo json_encode(['error' => 'Comment content exceeds maximum length of 1000 characters']);
				return;
			}

			// 插入评论
			$commentId = $this->postModel->insertComment(
				$data['post_id'],
				$data['user_id'],
				$data['content']
			);

			// 获取新插入的评论完整信息
			$newComment = $this->postModel->getCommentById($commentId);

			http_response_code(201);
			echo json_encode([
				'status' => 'success',
				'message' => 'Comment inserted successfully',
				'data' => [
					'comment_id' => $newComment['id'],
					'content' => $newComment['content'],
					'created_at' => $newComment['created_at'],
					'updated_at' => $newComment['updated_at'],
					'user' => [
						'id' => $newComment['user_id'],
						'username' => $newComment['username'],
						'avatar_url' => $newComment['avatar_url']
					]
				]
			]);

		} catch (PDOException $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => 'Database error: ' . $e->getMessage()
			]);
		} catch (Exception $e) {
			http_response_code(500);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}

	//  发帖
	public function releasePost()
	{
		try {
			$data = json_decode(file_get_contents('php://input'), true);

			// 基本数据验证
			if (
				empty($data['user_id']) || empty($data['category_id']) ||
				empty($data['title']) || empty($data['content'])
			) {
				throw new Exception('Missing required fields');
			}

			$postId = $this->postModel->insertPost(
				$data['user_id'],
				$data['category_id'],
				$data['title'],
				$data['content'],
				$data['status'] ?? '正常'
			);

			$newPost = $this->postModel->getNewPostById($postId);

			http_response_code(201);
			echo json_encode([
				'status' => 'success',
				'message' => 'Post released successfully',
				'data' => $newPost
			]);

		} catch (Exception $e) {
			http_response_code(400);
			echo json_encode([
				'status' => 'error',
				'message' => $e->getMessage()
			]);
		}
	}
}
?>